package org.ycx.upms.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.ycx.upms.dao.mapper.ISecUserMapper;
import org.ycx.upms.dao.mapper.ISecUserRoleMapper;
import org.ycx.upms.dao.model.SecUser;
import org.ycx.upms.dao.model.SecUserExample;
import org.ycx.upms.dao.model.SecUserRole;
import org.ycx.upms.dao.model.SecUserRoleExample;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by 杨 on 2017-06-26.
 */
@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private ISecUserMapper userMapper;

    @Autowired
    private ISecUserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SecUserExample suex = new SecUserExample();
        suex.createCriteria().andLoginNameEqualTo(username);
        List<SecUser> users = this.userMapper.selectByExample(suex);
        if (users != null && users.size() > 0) {
            SecUser user = users.get(0);
            SecUserRoleExample rex = new SecUserRoleExample();
            rex.createCriteria().andUserIdEqualTo(user.getUid());
            List<SecUserRole> roles = this.userRoleMapper.selectByExample(rex);
            List<GrantedAuthority> grants = new ArrayList<GrantedAuthority>();
            for (SecUserRole ur : roles) {
                grants.add(new SimpleGrantedAuthority(ur.getRoleId() + ""));
            }
            return new User(user.getLoginName(), user.getPasswd(), "1".equals(user.getUseState()), true, true, true, grants);
        } else {
            return new User(UUID.randomUUID().toString(), UUID.randomUUID().toString(), false, false, false, false, null);
        }
    }
}
